package persistance.dal;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;

import ucc.objects.CaisseDuJourDTO;
import exception.DataAccesException;

public class CaisseDuJourPersisterImpl implements CaisseDuJourPersister {

	private PreparedStatement queryInsert;
	private PreparedStatement queryUpdate;
	private static final String INSERT = "insert into caisse.caisses_du_jour (utilisateur, ouverture, fond_de_caisse_depart)"
			+ "values (?, ?, ?)";
	private static final String UPDATE = "update caisse.caisses_du_jour set "
			+ "fermeture=?, fond_de_caisse_fermeture=?, remuneration_utilisateur=?"
			+ "where id_caisse_du_jour=?";

	public CaisseDuJourPersisterImpl() {
		this.queryInsert = DalBackEndServices.INSTANCE.prepare(INSERT,
				Statement.RETURN_GENERATED_KEYS);
		this.queryUpdate = DalBackEndServices.INSTANCE.prepare(UPDATE);
	}

	@Override
	public void insert(CaisseDuJourDTO nouvelleCaisseDuJour) {
		try {
			queryInsert.setString(1, nouvelleCaisseDuJour.getUtilisateur()
					.getNomDUtilisateur());
			Timestamp time1 = new Timestamp(nouvelleCaisseDuJour.getOuverture()
					.getTimeInMillis());
			queryInsert.setTimestamp(2, time1);
			queryInsert.setDouble(3,
					nouvelleCaisseDuJour.getFondDeCaisseDeDepart());
			queryInsert.executeUpdate();
			ResultSet rs = queryInsert.getGeneratedKeys();
			while (rs.next()) {
				nouvelleCaisseDuJour.setId(rs.getInt(1));
			}
		} catch (SQLException sqlE) {
			sqlE.printStackTrace();
			throw new DataAccesException(
					"SQL/JDBC Connection, Statement, executeQuery problem \n",
					sqlE);
		}
	}

	@Override
	public void update(CaisseDuJourDTO caisseDuJour) {
		try {
			Timestamp time1 = new Timestamp(caisseDuJour.getFermeture()
					.getTimeInMillis());
			queryUpdate.setTimestamp(1, time1);
			queryUpdate.setDouble(2, caisseDuJour.getFondDeCaisseDeFermeture());
			queryUpdate.setDouble(3, caisseDuJour.getRemunerationUtilisateur());
			queryUpdate.setInt(4, caisseDuJour.getId());
			queryUpdate.execute();
		} catch (SQLException sqlE) {
			sqlE.printStackTrace();
			throw new DataAccesException(
					"SQL/JDBC Connection, Statement, executeQuery problem \n",
					sqlE);
		}
	}
}
